const Panel = require("../gmoon/basePanel");
const GUNSTATE = require("../states/gunstates");
const STATE = {
    NOLOAD : 1,
    OPEN : 2 ,
    CLOSE : 3 , 
    UNLOAD : 4
}
cc.Class({
    extends: Panel,

    properties: {
    },

    onLoad(){
        this.setAttr("_loaded" , false );
        $EBUS.on( "gun-start-evnet" , this.onGunMovingStart.bind(this) );
        $EBUS.on( "gun-moving-evnet" , this.onGunMoving.bind(this) );
        $EBUS.on( "gun-moving-end-evet" , this.onMoveEndCancel.bind(this) );
    },

    useResource(){
        return $RES.use(
            "fab-hb-item #合成台",
            "fab-pt-item #炮台",
            "fab-virus #病毒组件",
            "fab-gun",
            "fab-zidan",
            "fab-smzidan",

            "img-control-bg",
            "img-hbitem-bg",
            "img-ptitm-bg",
            //圈圈
            "img-rung-bg",

            "sound-shoot #射击声音",
            "sound-boom"
        );
    },

    tmpSuc(){
        $T.getScr($G.get("gamepanel")).sa("levSuccess","success");
    },

    load(){
        return new Promise(( res )=>{
            this.useResource()
            .then(( d )=>{
                let panel = this.childNode("panel");
                $T.setSprite( panel ,d["img-control-bg"] , [this.node.width ,]);

                let y = -(this.node.height-panel.height)/2;
                let panelPos = cc.v2(0, y);
                this.setState( STATE.OPEN );

                cc.tween(panel)
                .to( .3 , { position: panelPos } , {easing: 'sineOut'} )
                .call(()=>{
                    let hbpanel = this.child("panel > hbpanel"),
                        ptpanel = this.child("panel > paotais"),
                        viruspanel = $G.get("viruspanel"),
                        topos;
                    if( !this.getAttr("_loaded") ){
                        hbpanel.loadItems(),
                        ptpanel.loadItems();
                        this.setAttr("_loaded" , true );
                    }
        
                    topos = hbpanel.node.convertToWorldSpaceAR( cc.v2(0 , hbpanel.node.height/2 + ptpanel.node.height/2 ) );
                    let ptpos = {x : ptpanel.node.x , y:  (ptpanel.node.parent.height/2 + ptpanel.node.height/2)-80 }

                    cc.tween( ptpanel.node )
                    .to(.2 , ptpos )
                    .call(()=>{
                        ptpanel.resetPos();
                        res();
                    })
                    .start();
                })
                .start();
                //panel.setPosition( cc.v2(0, -(this.node.height-panel.height)/2 ) );
    
    
            })
        })
    },

    unload(){
        return new Promise(( res )=>{
            let panel = this.childNode("panel");
            this.child("panel > paotais").unload();
            
            this.setState(STATE.UNLOAD);

            cc.tween( panel )
            .to( .3 , { position: cc.v2(0 , -800) } , {easing: 'sineOut'} )
            .call(()=>{
                res();
            })
            .start();
        });
    },

    //当状态发生变化时
    onStateChanged( frmState , toState ){

    },

    _setCurent( node , flag ){
        flag = $T.selectValue( flag , true );
        $T.getScr(node).setGetGunState( flag );
    },

    onGunMovingStart( e ){
        let p = e ? e.getUserData() : {} , 
            target = p.event.target;
        let panel = this.childNode("panel");
        let gun = $T.getScr(target);
        if( this.isState(STATE.OPEN) && gun.isState(GUNSTATE.INBIGHEBING) ){
            
            this.onCtrlBtnClick( false );
            
        }
    },

    onMoveEndCancel( e ){
        let p = e ? e.getUserData() : {} , 
            target = p.event.target , 
            callback = p.callback;
        let last = this.getAttr("_lastMb");
        if(last){
            this._setCurent( last.node , false );
            $T.getScr(last.node).fitGun( target );
        }
        this.setAttr("_hbitems" , null);
        this.setAttr("_paotais" , null);
        callback && callback( !!last );
    },

    onGunMoving( e ){
        let d = e.getUserData();
        let target = d.event.target;
        let wdpos = target.parent.convertToWorldSpaceAR( target.getPosition() );

        wdpos = wdpos.add(cc.v2(0,target.height/2));

        let last = this.getAttr("_lastMb");
        let hbs = this.getAttr("_hbitems"),
            pts = this.getAttr("_paotais");
        let mpaotaiNode = this.childNode("panel > paotaibig");

        !(()=>{
            hbs = [];
            let n = this.children("panel > hbpanel > hbitem");
            for(let i in n){
                hbs.push({
                    node : n[i],
                    wdpos : n[i].parent.convertToWorldSpaceAR( n[i].getPosition() )
                })
            }
            this.setAttr("_hbitems" , hbs);
        })();
        
        !(()=>{
            pts = [];
            let n = this.children("panel > paotais > paotai");
            for(let i in n){
                pts.push({
                    node : n[i],
                    wdpos : n[i].parent.convertToWorldSpaceAR( n[i].getPosition() )
                })
            }
            pts.push({
                node : mpaotaiNode,
                wdpos : mpaotaiNode.parent.convertToWorldSpaceAR( mpaotaiNode.getPosition() )
            })
            this.setAttr("_paotais" , pts);
        })()

        let mb = null , l;
        for(let i in pts){
            l = wdpos.sub( pts[i].wdpos ).mag();
            if(l<100){
                mb = pts[i];
                break;
            }
        }
        
        for(let i=0 ; i<hbs.length && !mb; i++){
            l = wdpos.sub( hbs[i].wdpos ).mag();
            if(l < hbs[i].node.width*.7 ){
                mb = hbs[i];
                break;
            }
        }

        if(last && (!mb || last.node.uuid != mb.node.uuid) ){
            this._setCurent( last.node , false )
        }

        mb && this._setCurent( mb.node , true );
        this.setAttr("_lastMb" , mb);

        d.callback && d.callback();
    },

    onBuyGunBtn( e ){
        let target = e.target;
        $Animate.do("playUnPop" , target , 0 , {u:.1 });
        let hbScr = this.child("panel > hbpanel");

        let fn = ()=>{
            let eptHbitm =  hbScr.getEmptyItem();
            if( eptHbitm ){
                let gun = $G.get('poolGetByName' , 'gun');
                gun.setPosition(cc.v2(0,1000));
                $T.getScr(gun).setLevel(1);
                $T.getScr(eptHbitm).fitGun(gun);
            }
        }

        if( !this.isState(STATE.OPEN) ){
            this.onCtrlBtnClick( true , fn);
        }else fn();

    },

    onCtrlBtnClick( isCheckGunPos , cb ){
        isCheckGunPos = $T.selectValue(isCheckGunPos , true);
        let target = this.childNode("panel > conbtn");
        let winsize = cc.winSize;
        let panel = this.childNode("panel");
        let paotaibig = this.child("panel > paotaibig") , 
            bigGun = paotaibig.getGun();

        if( this.isState(STATE.OPEN) ){
            //cc.v2(0, -(this.node.height-panel.height)/2 );
            let y = -( (this.node.height-panel.height)/2 + (panel.height*1.7/3) );
            let cha = y - panel.y;
            cc.tween(panel)
            .to(.2 , { y : y })
            .call(()=>{
                cb && cb();
            })
            .start();

            
            if( bigGun && isCheckGunPos ){
                cc.tween( bigGun.node)
                .by(.2 , {y : cha})
                .start();
            }

            cc.tween(target)
            .to(.1 , {rotation : 180})
            .start();
            
            this.setState( STATE.CLOSE);
        }else{
            let y = -(this.node.height-panel.height)/2;
            let cha = y - panel.y;

            cc.tween( panel )
            .to(.2 , {y : y })
            .call(()=>{
                cb && cb();
            })
            .start();

            if( bigGun && isCheckGunPos ){
                cc.tween( bigGun.node)
                .by(.2 , {y : cha})
                .start();
            }

            cc.tween(target)
            .to(.1 , {rotation : 0})
            .start();

            this.setState( STATE.OPEN);
        }
    },

    update (dt) {

    },
});
